import { observer } from 'mobx-react-lite'
import React, { useEffect, useRef } from 'react'
import * as echarts from 'echarts'
import dayjs from 'dayjs'
import { storeAll } from '@/store'

const Cost: React.FC = () => {
	const chartRef = useRef<HTMLDivElement>(null)
	const { parkingLotTypeStore: { parkingLotType }, notesStore: { notes } } = storeAll
	const legend = parkingLotType.map(item => item.notes)
	const curMonth = dayjs().month()
	const newNotes = notes.filter(item => item.cost)
	const data: any[][] = Array(legend.length).fill(0).map(() => Array(3).fill(0))
	newNotes.forEach(item => {
		const mon = dayjs(item.outTime).month()
		const cha = curMonth - mon
		if (cha > 2) {
			return
		}

		if (data[legend.indexOf(item.notes)][cha]) {
			data[legend.indexOf(item.notes)][cha] += item.cost
		} else {
			data[legend.indexOf(item.notes)][cha] = item.cost
		}
	})
	useEffect(() => {
		if (!chartRef.current) return
		const seriesLabel = {
			show: true
		};
		const option: any = {
			title: {
				text: '近三个月收入统计'
			},
			tooltip: {
				trigger: 'axis',
				axisPointer: {
					type: 'shadow'
				}
			},
			legend: {
				data: legend
			},
			grid: {
				left: 100
			},
			toolbox: {
				show: true,
				feature: {
					saveAsImage: {}
				}
			},
			xAxis: {
				type: 'value',
				name: '收入',
				axisLabel: {
					formatter: '{value}'
				}
			},
			yAxis: {
				type: 'category',
				inverse: true,
				data: [curMonth + 1, curMonth, curMonth - 1],
				axisLabel: {
					formatter: function (value: any) {
						return value + "月"
					},
					margin: 20,
				}
			},
			series: data.map((item, index) => ({
				name: legend[index],
				type: 'bar',
				data: item,
				label: seriesLabel,
			}))
		};
		const chart = echarts.init(chartRef.current)
		chart.setOption(option)
		// 组件卸载
		return () => {
			chart.dispose()
		}
	}, [legend, curMonth, data])
	return <div ref={chartRef} style={{ width: "620px", height: "400px" }}></div>
}

export default observer(Cost)